<template>
	<view class="user" :class="[isDark?'dark':'', $store.state.AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6', 'min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px', 'background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back" :style="{'color':isDark?'#ffffff':'#000000'}"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}, {'color':isDark?'#ffffff':'#000000'}]">
					<text v-if="type=='setInfo'">{{$t('user.useredit.editprofile')}}</text>
					<text v-if="type=='setSafe'">{{$t('user.useredit.securityset')}}</text>
					<text v-if="type=='setPw'">{{$t('user.useredit.editpassword')}}</text>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @tap="userEdit">
					
				</view>
				<!--  #endif -->
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>

		<form>
			<block v-if="type=='setInfo'">
			<view class="user-edit-header margin-top" :style="{'background-size': 'cover', 'height': '450upx', 'display': 'flex', 'justify-content': 'center', 'align-items': 'center', 'background-image': 'url(' + userBg + ')'}">
				<view>
				<image :src="avatar"></image>
				<text class="cu-btn bg-gradual-blue radius" style="margin-right: 20upx;" @tap="toAvatar">{{$t('user.useredit.setavatar')}}</text>
				<text class="cu-btn bg-gradual-orange radius" @tap="toBg">{{$t('user.useredit.changeback')}}</text>
				</view>
			</view>
			
			<view class="cu-form-group margin-top" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.sex')}}</view>
				<radio-group class="block" @change="RadioChange">
					<label><text class="tn-margin-right-sm" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.nodisplay')}}</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='bm'?'checked':''"
							:checked="url=='bm'?true:false" value="bm"></radio>
					</label>
					<label><text class="tn-margin-right-sm" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.male')}}</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='man'?'checked':''"
							:checked="url=='man'?true:false" value="man"></radio>
					</label>
					<label><text class="tn-margin-right-sm" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.woman')}}</text>
						<radio class="cyan tn-margin-right-lg" :class="url=='woman'?'checked':''"
							:checked="url=='woman'?true:false" value="woman"></radio>
					</label>
				</radio-group>
			</view>
			<view class="cu-form-group" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.nickname')}}</view>
				<input :placeholder="$t('global.plsnickname')" name="input" v-model="screenName" :style="{'color':isDark?'#ffffff':'#000000'}"/>
			</view>
			<view class="cu-form-group align-start" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.personalprofile')}}</view>
				<textarea v-model="introduce" :placeholder="$t('user.useredit.plspersonalprofile')" :style="{'color':isDark?'#ffffff':'#000000'}"></textarea>
			</view>
			
			</block>
			<block v-if="type=='setSafe'">
			<view class="cu-form-group margin-top" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.username')}}</view>
				<input name="input" disabled="disabled" :value="name" :style="{'color':isDark?'#cccccc':'#666666'}"/>
			</view>
			<view class="cu-form-group" @tap="toEmail" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.email')}}</view>
				<input :placeholder="$t('user.useredit.unbound')" disabled="disabled" name="input" :value="mail" :style="{'color':isDark?'#cccccc':'#666666'}"/>
				<view class="action">
					<text class="cuIcon-right" :style="{'color':isDark?'#ffffff':'#000000'}"></text>
				</view>
			</view>
			<view class="cu-form-group" @tap="toPhone" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.phone')}}</view>
				<input :placeholder="$t('user.useredit.unbound')" disabled="disabled" name="input" :value="phone" :style="{'color':isDark?'#cccccc':'#666666'}"/>
				<view class="action">
					<text class="cuIcon-right" :style="{'color':isDark?'#ffffff':'#000000'}"></text>
				</view>
			</view>
			<view class="cu-form-group" @tap="toBind" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.useredit.thirdaccobind')}}</view>
				<view class="action">
					<text class="cuIcon-right" :style="{'color':isDark?'#ffffff':'#000000'}"></text>
				</view>
			</view>
			</block>
			<block v-if="type=='setPw'">
			<view class="cu-form-group margin-top" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.password')}}</view>
				<input placeholder="$t('global.plspassword')" v-model="password" name="input" :style="{'color':isDark?'#ffffff':'#000000'}"/>
			</view>
			<view class="cu-form-group" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
				<view class="title" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('global.surepassword')}}</view>
				<input placeholder="$t('global.plstrypassword')" v-model="repassword" name="input" :style="{'color':isDark?'#ffffff':'#000000'}"/>
			</view>
			</block>
			<view class="all-btn margin-top" v-if="type!='setSafe'">
				<view class="user-btn flex flex-direction">
					<button class="cu-btn bg-blue margin-tb-sm lg" @tap="userEdit">{{$t('user.useredit.saveedit')}}</button>
				</view>
			</view>
		</form>
		<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">{{$t('user.useredit.setavatar')}}</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<view>{{$t('user.useredit.programbindqq')}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>	
import darkModeMixin from '@/utils/darkModeMixin.js'
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	// #ifdef H5 || APP-PLUS 
	import {
		pathToBase64,
		base64ToPath
	} from '../../js_sdk/mmmm-image-tools/index.js'
	// #endif
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				uid: 0,
				name: '',
				screenName: '',
				password: '',
				repassword: '',
				mail: '',
				phone: "",
				url: 'bm',
				avatar: "",
				isHuaWei: this.$API.isHuaWei(),
				isTy: false,
				userBg: '',
				type: "",
				avatarNew: "",
				introduce: "",
				backif: 0,
				modalName: null,
				token: '',
				styleIndex: "",
			}
		},
		onPullDownRefresh() {

		},
		onShow() {
			var that = this;
			// #ifdef APP-PLUS
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
			that.userStatus();
			if (localStorage.getItem('toAvatar')) {
				var toAvatar = JSON.parse(localStorage.getItem('toAvatar'));
				that.avatarUpload(toAvatar.dataUrl);
			} else {
				
			}
		},
		onLoad(res) {
			var that = this;
			that.backif = res.backif;
			that.type = res.type;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			that.styleIndex = that.$API.GetStyleIndex();
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			validatePassword(password) {
				const regex = /^(?=.*[A-Za-z])(?=.*\d).{6,}$/;
				return regex.test(password);
			},
			userStatus() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				that.$Net.request({
					url: that.$API.userStatus(),
					data: {
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.uid = res.data.data.uid;
							that.screenName = res.data.data.screenName;
							that.name = res.data.data.name;
							that.mail = res.data.data.mail;
							that.url = res.data.data.url;
							that.token = res.data.data.token;
							that.avatar = res.data.data.avatar;
							that.userBg = res.data.data.userBg;
							that.introduce = res.data.data.introduce;
							that.phone = res.data.data.phone;
							if (localStorage.getItem('userinfo')) {
								var userInfo = JSON.parse(localStorage.getItem('userinfo'));
								if (userInfo.screenName) {
									that.screenName = userInfo.screenName;
								} else {
									that.screenName = userInfo.name;
								}
								if (res.data.data.customize) {
									userInfo.customize = res.data.data.customize;
								}
								if (res.data.data.lv) {
									userInfo.lv = res.data.data.lv;
								}
								if (res.data.data.isvip) {
									userInfo.isvip = res.data.data.isvip;
								}
								if (res.data.data.vip) {
									userInfo.vip = res.data.data.vip;
								}
								if (res.data.data.experience) {
									userInfo.experience = res.data.data.experience;
								}
								localStorage.setItem('userinfo', JSON.stringify(userInfo));
								// if(res.data.data.avatar){
								// 	that.userInfo = res.data.data.avatar;
								// }
							}

						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			validateString(str) {
				// 判断是否包含空格或中文空格
				if (/\s|　/.test(str)) {
					return false;
				}
				// 判断是否只包含空格
				if (/^\s+$/.test(str)) {
					return false;
				}
				return true;
			},
			userEdit() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				if (that.password != "") {
					if (!that.validatePassword(that.password)) {
						uni.showToast({
							title: that.$t('user.useredit.pwdnumletter6'),
							icon: 'none',
							duration: 1000,
							position: 'bottom',
						});
						return false
					}
					if (that.password != that.repassword) {
						uni.showToast({
							title: that.$t('global.twopassdisagree'),
							icon: 'none',
							duration: 1000,
							position: 'bottom',
						});
						return false
					}

				}
				if (that.screenName.length > 10) {
					uni.showToast({
						title: that.$t('user.useredit.nicknamelong'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false;
				}
				if (that.isValidString(that.screenName)) {
					uni.showToast({
						title: that.$t('user.useredit.nicknamenospace'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var data = {
					uid: that.uid,
					name: that.name,
					screenName: that.screenName,
					password: that.password,
					introduce: that.introduce,
					url: that.url,
				}
				if (that.avatarNew != '') {
					data.avatar = that.avatarNew;
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({

					url: that.$API.userEdit(),
					data: {
						"params": JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if (res.data.code == 1) {
							//保存用户信息
							if (that.password != "") {
								localStorage.removeItem('userinfo');
								localStorage.removeItem('token');
								
								var timer = setTimeout(function() {
									var styleIndex = that.styleIndex;
									uni.redirectTo({
										url: '/pages/home/' + styleIndex
									});
									clearTimeout('timer')
								}, 1000)
								
							} else {
								var userInfo = JSON.parse(localStorage.getItem('userinfo'));
								userInfo.screenName = that.screenName;
								userInfo.url = that.url;
								userInfo.introduce = that.introduce;
								if (that.avatarNew != '') {
									userInfo.avatar = that.avatarNew;
								}
								that.avatarNew = '';
								localStorage.setItem('userinfo', JSON.stringify(userInfo));
								if (that.backif == 1) {
									that.back();
								}
							}

						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			toEmail() {
				uni.navigateTo({
					url: '/pages/user/mailedit'
				});
			},
			toPhone() {
				uni.navigateTo({
					url: '/pages/user/phoneedit'
				});
			},
			toAddress() {
				uni.navigateTo({
					url: '/pages/user/address'
				});
			},
			toPay() {
				uni.navigateTo({
					url: '/pages/user/pay'
				});
			},
			toBg() {
				var that = this;
				if(that.isTy==false&&that.isHuaWei==1){
					that.showTC()
				}
				uni.navigateTo({
					url: '/pages/user/userBg'
				});
			},
			toAvatar() {
				var that = this;
				if(that.isTy==false&&that.isHuaWei==1){
					that.showTC()
				}
				uni.navigateTo({
					url: '/pages/user/userAvatar'
				});
			},
			toBind() {
				uni.navigateTo({
					url: '/pages/user/userbind'
				});
			},
			RadioChange(e) {
				this.url = e.detail.value
			},
			// #ifdef APP-PLUS
			//权限检测
			showTC(){
				var that = this;
				var tc1 = false;
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							uni.showModal({
								title: that.$t('global.permissionapply'),
								content: that.$t('global.permissionapplydesc'),
								cancelText: that.$t('common.cancel'),
								confirmText: that.$t('global.agree'),
								showCancel: true,
								confirmColor: '#000',
								cancelColor: '#666',
								success: (res) => {
									if (res.confirm) {
										tc1 = true;
										that.requestPermissions();
									}else{
										that.isTy = false
										tc1 = true;
									}
								}
							})
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						
					}
				);
				plus.android.checkPermission(_permissionID,
					granted => {
						if (granted.checkResult == -1) {
							if(!tc1){
								uni.showModal({
									title: that.$t('global.permissionapply'),
									content: that.$t('global.permissionapplydesc'),
									cancelText: that.$t('common.cancel'),
									confirmText: that.$t('global.agree'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											return that.requestPermissions();
										}else{
											that.isTy = false
										}
									}
								})
						}
						//还未授权当前查询的权限，打开权限申请目的自定义弹框
						that.$nextTick(() => {
							setTimeout(() => {
								that.ani = 'uni-' + that.type
							},30)
						})
					}
				},
				error => {
					console.log(error.message);
				}
			);
		},
		requestPermissions() {
			let _this = this;
			let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
			let _permissionID2 = 'android.permission.CAMERA';
			
			plus.android.checkPermission(_permissionID2,
				granted => {
					if (granted.checkResult == -1) {
						//还未授权当前查询的权限，打开权限申请目的自定义弹框
						_this.$nextTick(() => {
							setTimeout(() => {
								_this.ani = 'uni-' + _this.type
							},30)
						})
					}
				},
				error => {
					console.log(error.message);
				}
			);
			plus.android.requestPermissions([_permissionID2],
				(e) => {
					//关闭权限申请目的自定义弹框
					_this.ani = '';
					_this.$nextTick(() => {
						
					})
					if (e.granted.length > 0) {
						//当前查询权限已授权
						plus.android.checkPermission(_permissionID,
							granted => {
								if (granted.checkResult == -1) {
									//还未授权当前查询的权限，打开权限申请目的自定义弹框
									_this.$nextTick(() => {
										setTimeout(() => {
											_this.ani = 'uni-' + _this.type
										},30)
									})
								}
							},
							error => {
								console.log(error.message);
							}
						);
						plus.android.requestPermissions([_permissionID],
							(e) => {
								//关闭权限申请目的自定义弹框
								_this.ani = '';
								_this.$nextTick(() => {
									
								})
								if (e.granted.length > 0) {
									//当前查询权限已授权
									_this.isTy = true
								}
								if (e.deniedAlways.length > 0) {
									//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
									uni.showModal({
										title: _this.$t('global.fogettips'),
										content: _this.$t('global.noalbumpermiss'),
										cancelText: _this.$t('common.cancel'),
										confirmText: _this.$t('global.setitup'),
										showCancel: true,
										confirmColor: '#000',
										cancelColor: '#666',
										success: (res) => {
											if (res.confirm) {
												_this.goSetting();
											}else{
												_this.isTy = false
											}
										}
									})
								}
							})
					}
					if (e.deniedAlways.length > 0) {
						//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
						uni.showModal({
							title: _this.$t('global.fogettips'),
							content: _this.$t('global.nocamerapermiss'),
							cancelText: _this.$t('common.cancel'),
							confirmText: _this.$t('global.setitup'),
							showCancel: true,
							confirmColor: '#000',
							cancelColor: '#666',
							success: (res) => {
								if (res.confirm) {
									_this.goSetting();
								}else{
									_this.isTy = false
								}
							}
						})
					}
				})
			},
			//跳转手机系统设置
			goSetting() {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			},
			// #endif
			
			avatarUpload(base64) {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				base64ToPath(base64)
					.then(path => {
						var file = path;
						const uploadTask = uni.uploadFile({
							url: that.$API.upload(),
							filePath: file,
							//  header: {
							// "Content-Type": "multipart/form-data",
							// },
							name: 'file',
							formData: {
								'token': token
							},
							success: function(uploadFileRes) {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);

								var data = JSON.parse(uploadFileRes.data);
								if (data.code == 1) {
									// uni.showToast({
									// 	title: data.msg,
									// 	icon: 'none'
									// })
									that.avatar = data.data.url;
									that.avatarNew = data.data.url;
									localStorage.removeItem('toAvatar');
									that.userEdit();
									//console.log(that.avatar)

								} else {
									uni.showToast({
										title: that.$t('user.useredit.avataruploaderr'),
										icon: 'none'
									})
								}
							},
							fail: function() {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
							}


						});
					})
					.catch(error => {
						console.error("失败" + error)
					})
			},
			isValidString(str) {
				return /\s/g.test(str);
			}
		}
	}
</script>

<style>
	.radius{
		border-radius: 100upx;
	}
</style>